import { _decorator, Component, Node, input, NodeEventType, Input, EventTouch, v3, Vec3, math, CCFloat } from 'cc';
import { VirtualInput } from '../input/VirtualInput';
const { ccclass, property } = _decorator;

@ccclass('UIJoystick')
export class UIJoystick extends Component {
    @property(Node)
    private bg: Node = null
    @property(Node)
    private thumbnail: Node = null
    @property({ type: CCFloat })
    private radius: number = 130

    private initPosition: Vec3 = v3()
    start() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this)

        //记录初始状态的位置
        this.initPosition = this.bg.worldPosition.clone()
    }

    update(deltaTime: number) {

    }
    private onTouchStart(event: EventTouch) {
        // 移动bg到点击位置
        let v2 = event.touch.getUILocation()
        this.bg.setWorldPosition(v2.x, v2.y, 0)
    }
    private onTouchMove(event: EventTouch) {
        // 移动thumbnial并限定范围
        let v2 = event.touch.getUILocation()

        let worldPosition = new Vec3(v2.x, v2.y, 0)
        let localPosition = new Vec3()

        //将世界坐标转成本地坐标
        this.bg.inverseTransformPoint(localPosition, worldPosition)
        let len = localPosition.length()
        localPosition.normalize()
        localPosition.multiplyScalar(math.clamp(len, 0, this.radius)) //clamp将len在0-radius上取值
        this.thumbnail.setPosition(localPosition)

        VirtualInput.horizontal = this.thumbnail.position.x / this.radius
        VirtualInput.vertical = this.thumbnail.position.y / this.radius
    }
    private onTouchEnd(event: EventTouch) {
        //位置归位
        this.bg.setWorldPosition(this.initPosition)
        this.thumbnail.setPosition(Vec3.ZERO)
        VirtualInput.horizontal = 0
        VirtualInput.vertical = 0
    }

}


